package controllers

import (
	"mime/multipart"
	"net/http"
	"strconv"

	"my-go-project/config"
	"my-go-project/model"
	"my-go-project/utils/token"

	"github.com/gin-gonic/gin"
)

// /api/register的请求体
type ReqRegister struct {
	UserName     string                `json:"UserName" binding:"required"`
	Email        string                `json:"Email" binding:"required"`
	Password     string                `json:"Password" binding:"required"`
	ContactType  string                `json:"ContactType"`
	Contact      string                `json:"Contact"`
	ProfilePhoto *multipart.FileHeader `json:"ProfilePhoto"`
}

func Register(c *gin.Context) {
	var req ReqRegister
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	user := model.User{
		UName:        req.UserName,
		Email:        req.Email,
		Password:     req.Password,
		Contact:      req.Contact,
		ContactType:  req.ContactType,
		ProfilePhoto: "PhotoSrc",
	}

	id, _ := model.GetLastID()
	var path string
	if req.ProfilePhoto.Filename != "" {
		path = config.AppConfig.File.Path + strconv.Itoa(id+1) + "/ProfilePhoto.png"
		err = c.SaveUploadedFile(req.ProfilePhoto, config.AppConfig.File.AbsolutePath+path)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save the file"})
			return
		}
	} else {
		path = config.AppConfig.File.DefaultPhoto
	}

	user.ProfilePhoto = path
	_, err = user.SaveUser()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "register failed"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "register success",
	})
}

type ReqLogin struct {
	Email    string `json:"Email" binding:"required"`
	Password string `json:"Password" binding:"required"`
}

func Login(c *gin.Context) {
	var req ReqLogin
	if err := c.ShouldBindBodyWithJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	u := model.User{
		Email:    req.Email,
		Password: req.Password,
	}

	// 调用 models.LoginCheck 对用户名和密码进行验证
	token, err := model.LoginCheck(u.Email, u.Password)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"result": 0,
		})
		return
	}

	id, _ := model.GetIDByEmail(req.Email)
	c.JSON(http.StatusOK, gin.H{
		"token":  token,
		"result": 1,
		"id":     id,
	})
}

func CurrentUser(c *gin.Context) {
	// 从token中解析出user_id
	user_id, err := token.ExtractTokenID(c)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	// 根据user_id从数据库查询数据
	u, err := model.GetUserByID(int(user_id))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "success",
		"data":    u,
	})
}
